package application;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class TelephoneNumberWrapper implements Validatable {
    private String text;

    private TelephoneNumberWrapper() {
    }

    public TelephoneNumberWrapper(String text) {
        this.text = text.trim();
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    @Override
    public boolean isValid() {
        return text.matches(ValidationPattern);
    }


    /**
     * 使用正则表达式对固定电话座机号码进行字符串校验
     *
     * 支持如下格式：
     *  010-88888888
     *  01088888888
     *  0532-89078907
     *  053289078907
     */
    protected final static String ValidationPattern =
            "^0[1-9]\\d{1,2}-?\\d{8}$";

    public String findAreaCode() {
        for (int i = 0; i < text.length(); i++) {
            String prefix = text.substring(0, i);
            if (isAreaCode(prefix)) {
                return prefix;
            }
        }
        return null;
    }

    private static boolean isAreaCode(String prefix) {
        final Set<String> areas = new HashSet<>(Arrays.asList("0571", "021", "010"));
        return areas.contains(prefix);
    }
}
